
<template>
    <view class="container">
      <!-- 顶部导航栏 -->
      <view class="header-section">
        <!-- 月份选择器 -->
        <view class="month-selector">
          <uni-icons type="left" size="20" color="#666" @click="changeMonth(-1)" class="cursor-pointer"></uni-icons>
          <text class="month-text">{{ formatMonth(currentMonth) }}</text>
          <uni-icons type="right" size="20" color="#666" @click="changeMonth(1)" class="cursor-pointer"></uni-icons>
        </view>
      </view>
  
      <!-- 日历视图区域 -->
      <view class="calendar-section">
        <!-- 月度统计卡片 -->
        <view class="monthly-stats">
          <view class="stats-header">
            <text class="stats-title">本月统计</text>
            <text class="stats-subtitle">{{ formatMonth(currentMonth) }}</text>
          </view>
          <view class="stats-grid">
            <view class="stat-item">
              <text class="stat-value">{{ formatNumber(monthlyStats.totalCalories) }}</text>
              <text class="stat-label">总热量</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ formatNumber(monthlyStats.averageCalories) }}</text>
              <text class="stat-label">平均热量</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ monthlyStats.recordDays }}</text>
              <text class="stat-label">记录天数</text>
            </view>
            <view class="stat-item">
              <text class="stat-value">{{ monthlyStats.targetDays }}</text>
              <text class="stat-label">达标天数</text>
            </view>
          </view>
          
          <!-- 达标率进度条 -->
          <view class="progress-section" v-if="monthlyStats.recordDays > 0">
            <view class="progress-header">
              <text class="progress-label">达标率</text>
              <text class="progress-value">{{ Math.round((monthlyStats.targetDays / monthlyStats.recordDays) * 100) }}%</text>
            </view>
            <view class="progress-bar">
              <view 
                class="progress-fill" 
                :style="{ width: Math.min((monthlyStats.targetDays / monthlyStats.recordDays) * 100, 100) + '%' }"
              ></view>
            </view>
          </view>
        </view>

        <!-- 星期表头 -->
        <view class="week-header">
          <text class="week-day" v-for="day in weekDays" :key="day">{{ day }}</text>
        </view>
        
        <!-- 日历网格 -->
        <view class="calendar-grid">
          <view 
            class="date-cell cursor-pointer" 
            v-for="(date, index) in calendarDates" 
            :key="index"
            :class="{ 
              'other-month': !date.isCurrentMonth,
              'selected': selectedDate && date.date === selectedDate.date,
              'today': isToday(date)
            }"
            @click="selectDate(date)"
          >
            <text class="date-number">{{ date.day }}</text>
            <view class="calorie-info" v-if="date.isCurrentMonth && date.calories > 0">
              <text class="calorie-value">{{ date.calories }}</text>
              <view class="calorie-indicator" :class="getCalorieStatus(date.calories)"></view>
            </view>
          </view>
        </view>
      </view>
  
      <!-- 底部详情面板 -->
      <view class="detail-panel" :class="{ 'show': selectedDate }">
        <view class="panel-header">
          <text class="panel-title">{{ formatSelectedDate(selectedDate) }}</text>
          <uni-icons type="close" size="20" color="#666" @click="closeDetail" class="cursor-pointer"></uni-icons>
        </view>
        
        <scroll-view scroll-y="true" class="detail-content">
          <view class="daily-summary">
            <view class="summary-item">
              <text class="summary-label">总热量</text>
              <text class="summary-value">{{ selectedDate?.calories || 0 }} kcal</text>
            </view>
            <view class="summary-item">
              <text class="summary-label">目标完成度</text>
              <text class="summary-value">{{ getCompletionRate(selectedDate?.calories || 0) }}%</text>
            </view>
          </view>
          
          <view class="food-records">
            <text class="section-subtitle">食物记录</text>
            <view class="food-list" v-if="selectedDate && selectedDate.foods.length > 0">
              <view class="food-item" v-for="(food, index) in selectedDate.foods" :key="index">
                <image class="food-image" :src="food.image" mode="aspectFill"></image>
                <view class="food-info">
                  <text class="food-name">{{ food.name }}</text>
                  <text class="food-portion">{{ food.portion }}</text>
                  <text class="food-time">{{ food.time }}</text>
                </view>
                <view class="food-calories">
                  <text class="calories-value">{{ food.calories }}</text>
                  <text class="calories-unit">kcal</text>
                </view>
              </view>
            </view>
            <view class="empty-state" v-else>
              <uni-icons type="info" size="48" color="#ddd"></uni-icons>
              <text class="empty-text">当日暂无记录</text>
            </view>
          </view>
        </scroll-view>
      </view>
  
      <!-- 遮罩层 -->
      <view class="overlay" :class="{ 'show': selectedDate }" @click="closeDetail"></view>
    </view>
  </template>
  
  <script>
  export default {
    data() {
      return {
        currentMonth: new Date(),
        selectedDate: null,
        weekDays: ['一', '二', '三', '四', '五', '六', '日'],
        targetCalories: 2000,
        historyData: {}
      }
    },
    computed: {
      calendarDates() {
        const year = this.currentMonth.getFullYear()
        const month = this.currentMonth.getMonth()
        const firstDay = new Date(year, month, 1)
        const lastDay = new Date(year, month + 1, 0)
        const firstDayOfWeek = firstDay.getDay() === 0 ? 7 : firstDay.getDay()
        const daysInMonth = lastDay.getDate()
        const dates = []
        // 添加上个月的日期
        const prevMonth = new Date(year, month - 1, 0)
        for (let i = firstDayOfWeek - 1; i > 0; i--) {
          const day = prevMonth.getDate() - i + 1
          const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
          dates.push({
            date: dateStr,
            day,
            isCurrentMonth: false,
            calories: 0,
            foods: []
          })
        }
        // 添加当月的日期
        for (let day = 1; day <= daysInMonth; day++) {
          const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
          const dayData = this.historyData[dateStr]
          dates.push({
            date: dateStr,
            day,
            isCurrentMonth: true,
            calories: dayData ? dayData.calories : 0,
            foods: dayData ? dayData.foods : []
          })
        }
        // 添加下个月的日期
        const remainingCells = 42 - dates.length
        for (let day = 1; day <= remainingCells; day++) {
          const dateStr = `${year}-${String(month + 2).padStart(2, '0')}-${String(day).padStart(2, '0')}`
          dates.push({
            date: dateStr,
            day,
            isCurrentMonth: false,
            calories: 0,
            foods: []
          })
        }
        return dates
      },
      monthlyStats() {
        const year = this.currentMonth.getFullYear()
        const month = this.currentMonth.getMonth()
        const daysInMonth = new Date(year, month + 1, 0).getDate()
        
        let totalCalories = 0
        let recordDays = 0
        let targetDays = 0
        
        // 遍历当月的每一天
        for (let day = 1; day <= daysInMonth; day++) {
          const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`
          const dayData = this.historyData[dateStr]
          
          if (dayData && dayData.calories > 0) {
            totalCalories += dayData.calories
            recordDays++
            
            // 判断是否达标（在目标热量的80%-120%范围内）
            if (dayData.calories >= this.targetCalories * 0.8 && dayData.calories <= this.targetCalories * 1.2) {
              targetDays++
            }
          }
        }
        
        const averageCalories = recordDays > 0 ? Math.round(totalCalories / recordDays) : 0
        
        return {
          totalCalories,
          averageCalories,
          recordDays,
          targetDays
        }
      }
    },
    methods: {
      formatMonth(date) {
        return `${date.getFullYear()}年${date.getMonth() + 1}月`
      },
      formatSelectedDate(date) {
        if (!date) return ''
        const dateObj = new Date(date.date)
        return `${dateObj.getFullYear()}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日`
      },
      changeMonth(direction) {
        const newMonth = new Date(this.currentMonth)
        newMonth.setMonth(newMonth.getMonth() + direction)
        this.currentMonth = newMonth
        this.selectedDate = null
        // 月份改变时重新计算统计数据
        this.$forceUpdate()
      },
      selectDate(date) {
        if (!date.isCurrentMonth) return
        this.selectedDate = date
      },
      closeDetail() {
        this.selectedDate = null
      },
      isToday(date) {
        const today = new Date()
        const dateObj = new Date(date.date)
        return dateObj.toDateString() === today.toDateString()
      },
      getCalorieStatus(calories) {
        if (calories === 0) return 'no-record'
        if (calories < this.targetCalories * 0.8) return 'under'
        if (calories > this.targetCalories * 1.2) return 'over'
        return 'normal'
      },
      getCompletionRate(calories) {
        return Math.round((calories / this.targetCalories) * 100)
      },
      formatNumber(num) {
        if (num >= 1000) {
          return (num / 1000).toFixed(1) + 'k'
        }
        return num.toString()
      },
      loadHistoryData() {
        // 从本地存储加载历史数据
        const savedHistoryData = uni.getStorageSync('historyData');
        if (savedHistoryData) {
            this.historyData = JSON.parse(savedHistoryData);
            console.log('加载历史数据:', this.historyData);
        }
        
        // 加载目标热量设置
        const savedTarget = uni.getStorageSync('targetCalories');
        if (savedTarget) {
            this.targetCalories = Number(savedTarget);
        }
      }
    },
    onLoad() {
      this.loadHistoryData();
    },
    onShow() {
      // 每次显示页面时重新加载数据
      this.loadHistoryData();
    },
    mounted() {
      this.currentMonth = new Date()
    }
  }
  </script>
  
  <style>
  page {
    height: 100%;
  }
  
  .container {
    height: 100%;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    display: flex;
    flex-direction: column;
  }
  
  .cursor-pointer {
    cursor: pointer;
  }
  
  /* 顶部导航栏 */
  .header-section {
    background: #fff;
    padding: 32rpx;
    border-radius: 0 0 32rpx 32rpx;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    flex-shrink: 0;
  }
  
  .nav-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;
  }
  
  .back-button {
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12rpx;
    background: #f8f9fa;
    text-decoration: none;
  }
  
  .nav-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
  
  .nav-placeholder {
    width: 48rpx;
    height: 48rpx;
  }
  
  .month-selector {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .month-text {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  /* 日历视图区域 */
  .calendar-section {
    flex: 1;
    padding: 32rpx;
    overflow: auto;
  }

  /* 月度统计卡片 */
  .monthly-stats {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 24rpx;
    padding: 32rpx;
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
    margin-bottom: 24rpx;
    display: flex;
    flex-direction: column;
    gap: 24rpx;
  }

  .stats-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stats-title {
    font-size: 20px;
    font-weight: 600;
    color: #fff;
  }

  .stats-subtitle {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
  }

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24rpx;
  }

  .stat-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12rpx;
    padding: 16rpx;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 16rpx;
    backdrop-filter: blur(10px);
  }

  .stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #fff;
  }

  .stat-label {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
  }

  /* 进度条样式 */
  .progress-section {
    margin-top: 16rpx;
  }

  .progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
  }

  .progress-label {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.9);
  }

  .progress-value {
    font-size: 14px;
    font-weight: 600;
    color: #fff;
  }

  .progress-bar {
    width: 100%;
    height: 8rpx;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 4rpx;
    overflow: hidden;
  }

  .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #4CAF50, #8BC34A);
    border-radius: 4rpx;
    transition: width 0.3s ease;
  }
  
  .week-header {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rpx;
    margin-bottom: 16rpx;
  }
  
  .week-day {
    text-align: center;
    font-size: 14px;
    color: #666;
    padding: 16rpx 0;
  }
  
  .calendar-grid {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 8rpx;
    background: #fff;
    border-radius: 24rpx;
    padding: 24rpx;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  }
  
  .date-cell {
    aspect-ratio: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 12rpx;
    position: relative;
    transition: all 0.2s ease;
    gap: 8rpx;
    padding: 8rpx;
  }
  
  .date-cell:hover {
    background: #f8f9fa;
  }
  
  .date-cell.other-month {
    opacity: 0.3;
  }
  
  .date-cell.selected {
    background: #4CAF50;
    color: #fff;
  }
  
  .date-cell.selected .date-number {
    color: #fff;
  }
  
  .date-cell.selected .calorie-value {
    color: #fff;
  }
  
  .date-cell.today {
    background: #e8f5e8;
  }
  
  .date-cell.today .date-number {
    color: #4CAF50;
    font-weight: 600;
  }
  
  .date-number {
    font-size: 16px;
    color: #333;
    font-weight: 500;
  }
  
  .calorie-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4rpx;
  }
  
  .calorie-value {
    font-size: 10px;
    color: #666;
  }
  
  .calorie-indicator {
    width: 24rpx;
    height: 4rpx;
    border-radius: 2rpx;
  }
  
  .calorie-indicator.normal {
    background: #4CAF50;
  }
  
  .calorie-indicator.under {
    background: #FFC107;
  }
  
  .calorie-indicator.over {
    background: #FF5722;
  }
  
  .calorie-indicator.no-record {
    background: #E0E0E0;
  }
  
  /* 底部详情面板 */
  .detail-panel {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100vw;
    background: #fff;
    border-radius: 32rpx 32rpx 0 0;
    max-height: 60%;
    transform: translateY(100%);
    transition: transform 0.3s ease;
    z-index: 1000;
    display: flex;
    flex-direction: column;
  }
  
  .detail-panel.show {
    transform: translateY(0);
  }
  
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;
  }
  
  .panel-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }
  
  .detail-content {
    flex: 1;
    overflow: auto;
    padding: 0 0 32rpx 0;
    box-sizing: border-box;
  }
  
  .daily-summary {
    display: flex;
    justify-content: space-around;
    padding: 32rpx 0;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 32rpx;
  }
  
  .summary-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
  }
  
  .summary-label {
    font-size: 14px;
    color: #666;
  }
  
  .summary-value {
    font-size: 18px;
    font-weight: 600;
    color: #4CAF50;
  }
  
  .food-records {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    padding-left: 20rpx;
    padding-right: 20rpx;
  }
  
  .section-subtitle {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  .food-list {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }
  
  .food-item {
    display: flex;
    align-items: center;
    padding: 24rpx;
    background: #f8f9fa;
    border-radius: 16rpx;
    gap: 24rpx;
  }
  
  .food-image {
    width: 80rpx;
    height: 80rpx;
    border-radius: 12rpx;
    flex-shrink: 0;
  }
  
  .food-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;
  }
  
  .food-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }
  
  .food-portion {
    font-size: 14px;
    color: #666;
  }
  
  .food-time {
    font-size: 12px;
    color: #999;
  }
  
  .food-calories {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
  
  .calories-value {
    font-size: 18px;
    font-weight: bold;
    color: #4CAF50;
  }
  
  .calories-unit {
    font-size: 12px;
    color: #666;
  }
  
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 0;
    gap: 24rpx;
  }
  
  .empty-text {
    font-size: 14px;
    color: #999;
  }
  
  /* 遮罩层 */
  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
    z-index: 999;
  }
  
  .overlay.show {
    opacity: 1;
    visibility: visible;
  }
  </style>
  